/*
* ============================================================================
* 功能描述 ：adc功能
* 作者       ：ggls
* 创建日期 ：2024.04.10
* ----------------------------------------------------------------------------
* 更新历史 ：
*	日期 　　- 修改者   : 更新内容描述
*
* ============================================================================
*/

#include "main.h"
#define ADC_LDO_2V   1
#define ADC_LDO_2P4V 2


void ADC_INIT()
{
	ADCON0 = 0B00000001;   //	
	ADCON1 = 0B00000010;	
	
	TRISB6 = 1;
	ANS14 = 1;

	ADON = 1;

}


unsigned int Read_ADC(unsigned char ADCchannel, unsigned char ADCLDORef) 
{
    unsigned int Adc_Result;
    unsigned char i = 200;
    
    unsigned char adc_ref_bits = (ADCLDORef == ADC_LDO_2V) ? 0x05 : (ADCLDORef == ADC_LDO_2P4V) ? 0x06 : 0x00;
    ADCON1 = adc_ref_bits | (ADCchannel & 0b00000011);
    CHS4 = (ADCchannel >= 16) ? 1 : 0;
    ADCchannel &= 0b00000011;
    
    ADCON0 &= 0b11000011;
    ADCON0 |= ADCchannel << 2;
    asm("nop");
    GODONE = 1;
    
    while (GODONE == 1 && i > 0) {
        i--;
        asm("nop");
    }
    
    Adc_Result = (ADRESH << 4) | (ADRESL >> 4);
    
    return Adc_Result;
}


